<?php

namespace Manager;

use W3\Util;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 附件编辑管理基类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Attach extends Attachs
{
    /**
     * 插入附件
     *
     * @access public
     * @param array $attachs 附件结构数组
     * @return integer
     */
    public function addAttach(array $values)
    {
		return $this->addAttachs($values);
    }

    /**
     * 更新附件
     *
     * @access public
     * @param array $aid 附件aid
     * @param array $attachs 附件结构数组
     * @return integer
     */
    public function updateAttach(int $aid, array $values)
    {
        /** 更新数据 */
		return $this->updateAttachs($aid, $values);
    }

    /**
     * 删除附件
     *
     * @access public
     * @param int $aid 附件aid
     * @return integer
     */
    public function deleteAttach($aid)
    {
        $attach = $this->db
			->select()
		    ->from('table.attachs')
            ->where('table.attachs.aid = ?', $aid)
            ->limit(1)
		    ->fetch();

        if (empty($attach)) {
			return ;
		}

		# 删除文件
        $this->widget('W3\Uploader')->delete($attach);
		
	    # 删除数据
		return $this->deleteAttachs($aid);
    }
	
    /**
     * 计算图片数，和非图片文件数
     *
     * @access public
     * @param string $type
     * @param integer|null $id
     * @param integer|null $uid
     * @return array
     */
    public function findNums(string $type, ?int $id = null, ?int $uid = null)
    {
		$images = $files = 0;
		$select = $this->db
			->select('table.attachs.isImage')
			->from('table.attachs')
			->where('table.attachs.type = ?', $type);

		isset($id) && $select->where('table.attachs.id = ?', $id);
		isset($uid) && $select->where('table.attachs.uid = ?', $uid);
		
		$attachlist = $select->get();
		
        foreach ($attachlist as $attach) 
		{
            if ($attach['isImage']) {
				++$images;
			} else {
				++$files;
			}
        }
		
		return !empty($attachlist) ? [$images, $files] : [];
    }
	
    /**
     * 同步附件
     *
     * @access public
     * @param string $type
     * @param integer $id
     * @return array
     */
    public function sync(string $type, int $id, int $uid)
    {
		# 同步 id == 0 的
		return $this->db
			->update('table.attachs')
		    ->where('table.attachs.type = ? AND table.attachs.id = ? AND table.attachs.uid = ?', $type, 0, $uid)
		    ->rows(['id'=>$id])
		    ->affected();
    }
	
    /**
     * 删除附件
     *
     * @access public
     * @param integer $id
     * @return void
     */
    public function remove(string $type, int $id)
    {
		$select = $this->db
			->select('table.attachs.aid')
			->from('table.attachs')
			->where('table.attachs.type = ? AND table.attachs.id = ?', $type, $id)
			->get();
			
		/** 删除 */
	    foreach($attachlist as $value) 
		{
			$this->deleteAttach($value['aid']);
		}
    }
	
}

